using AutoMapper;
using B.S.XZYData.Api.Read.Application.Command.Product;
using B.S.XZYData.Api.Read.Dto.Product;
using B.S.XZYData.Domain.LJC;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure.Interface;
using MediatR;
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.XZYData.Api.Read.Application.Handler.Product
{
    /// <summary>
    /// 根据ID获取产品详情处理器
    /// </summary>
    public class GetProductByIdHandler : IRequestHandler<GetProductByIdCommand, ApiResult<ProductDto>>
    {
        private readonly IBaseRepository<ProductModel> _productRepo;
        private readonly IMapper _mapper;

        public GetProductByIdHandler(
            IBaseRepository<ProductModel> productRepo,
            IMapper mapper)
        {
            _productRepo = productRepo;
            _mapper = mapper;
        }

        public async Task<ApiResult<ProductDto>> Handle(GetProductByIdCommand request, CancellationToken cancellationToken)
        {
            var res = new ApiResult<ProductDto>();

            try
            {
                // 根据ID查找产品
                var products = _productRepo.GetAll()
                    .Where(x => x.Id == request.Id)
                    .ToList();

                if (products.Count == 0)
                {
                    res.Code = ApiEnum.Fail;
                    res.Msg = "产品不存在";
                    res.Data = null;
                    return res;
                }

                var product = products.First();

                // 映射到 DTO
                var productDto = _mapper.Map<ProductDto>(product);

                res.Code = ApiEnum.Success;
                res.Msg = "查询成功";
                res.Data = productDto;
            }
            catch (Exception ex)
            {
                res.Code = ApiEnum.Error;
                res.Msg = $"查询失败：{ex.Message}";
                res.Data = null;
            }

            return res;
        }
    }
} 